import { QNURL } from "@/config/urlConfig";
import { reactive, ref, onMounted, computed, nextTick } from "vue";
import {
  getArticleDetail,
  getAllcommentList,
  articleComment
} from "@/api/community/index";
import { useRoute } from "vue-router";
import { getUserInfo } from "@/api/user/user";
import { useUserStore } from "@/store/modules/user";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import Prism from "prismjs";

export function useArticle() {
  const route = useRoute();
  const router = useRouter();

  const articleId = route.query.articleId || "";

  const userStore = useUserStore();

  const userInfo = computed(() => userStore.userInfo);

  const token = computed(() => userStore.token);

  let articleData = reactive<any>({});

  const commentList = ref<Array<any>>([]);

  async function getArticleDetailFun() {
    try {
      const res = await getArticleDetail({ id: articleId });

      articleData = Object.assign(articleData, res.data);
      nextTick(() => {
        Prism.highlightAll();
      });
    } catch {
      throw new Error("获取文章详情失败");
    }
  }

  async function getArticleCommentListFun() {
    try {
      const res = await getAllcommentList({ articleId });

      commentList.value = res.data;

      console.log(commentList.value);
    } catch {
      throw new Error("获取文章评论列表失败");
    }
  }

  async function sendBtn(val: string, data?: any) {
    if (!token.value) {
      ElMessage.warning("登入后才能评论！");
      return;
    }
    try {
      const rootCmId = data?.rootCommentId ? data.rootCommentId : data?.id;
      const res = await articleComment({
        articleId,
        content: val,
        userId: userInfo.value.userId,
        rootCommentId: data ? rootCmId : "",
        toUserId: data ? data.userId : ""
      });
      getArticleCommentListFun();
      ElMessage.success(res.msg);
    } catch {
      throw new Error("发送评论失败");
    }
  }

  let userInfoData = reactive<any>({
    avatar: "",
    email: "",
    id: "",
    nickName: "",
    phonenumber: "",
    sex: null,
    userName: ""
  });

  async function getUserInfoFun() {
    try {
      const res = await getUserInfo({ id: articleData.userId });
      userInfoData = Object.assign(userInfoData, res.data);
      userInfoData.avatar = QNURL + userInfoData.avatar;
    } catch {
      throw new Error("获取用户信息失败");
    }
  }

  const avatarClickHandle = (data: any) => {
    console.log(data);
    router.replace({
      path: "/home",
      query: {
        id: data.id
      }
    });
  };

  onMounted(async () => {
    await getArticleDetailFun();
    getArticleCommentListFun();
    getUserInfoFun();
  });

  return { articleData, commentList, userInfoData, sendBtn, avatarClickHandle };
}
